# Python迭代器及其用法
class listDemo:
    def __init__(self):
        self.__data = []
        self.__step = 0
    
    def __next__(self):
        if self.__step <= 0:
            raise StopIteration
        self.__step -= 1
        # 返回下一个元素
        return self.__data[self.__step]
    
    def __iter__(self):
        # 实例对象本身就是迭代器对象，因此直接返回 self 即可
        return self
    
    # 添加元素
    def __setitem__(self, key, value):
        self.__data.insert(key, value)
        self.__step += 1
        
mylist = listDemo()
mylist[0] = 1
mylist[1] = 2
for i in mylist:
    print(i)
print()

# 将列表转换为迭代器
myIter = iter([1, 2, 3])
# 依次获取迭代器的下一个元素
print(myIter.__next__())
print(myIter.__next__())
print(myIter.__next__())
#print(myIter.__next__()) # StopIteration
print()

class listDemo:
    def __init__(self):
        self.__data = []
        self.__step = 0
    
    def __setitem__(self, key, value):
        self.__data.insert(key, value)
        self.__step += 1
    
    # 使该类实例对象成为可调用对象
    def __call__(self):
        self.__step -= 1
        return self.__data[self.__step]

mylist = listDemo()
mylist[0] = 1
mylist[1] = 2
# 将 mylist 变为迭代器
a = iter(mylist, 1)
print(a.__next__())
print(a.__next__()) # StopIteration
